package cn.dida.controller;

import java.io.*;
import java.util.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.dida.model.*;
import cn.dida.service.LgsDepotService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cn.dida.service.LgsService;

@Controller
public class LgsController extends BaseController {

	@Autowired
	private LgsService lgsService;

	@Autowired
	private LgsDepotService LgsDepotService;

	/**
	 * 批次查询
	 * @param request
	 * @param batchNnb  批次号
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/batchsel")
	public ModelAndView getListByBatch(HttpServletRequest request,String batchNnb, Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);
		Map<String, Object> paramMap = getSimpleRequestParamMap(request);
		page = (page == null || page < 1) ? 1 : page;
		Pageable<Map<String,Object>> pagelist = lgsService.queryLgsInfoByBatch(userSession.getCompanyId(),batchNnb, page);
//		pagelist.setRquesturl(request, paramMap);
		model.put("pagelist", pagelist);
		model.put("batchNnb", batchNnb);
		return new ModelAndView("lgs_batch_list").addAllObjects(model);
	}

	/**
	 * 批次查询数据导出
	 * @param request
	 * @param response
	 * @param batchNub
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/batchExport")
	public String batchExport(HttpServletRequest request, HttpServletResponse response ,
								   String batchNub) throws Exception {



		UserSession userSession = getUserSession(request);

		List<Map<String,Object>> exportList = lgsService.batchExport(userSession.getCompanyId(), batchNub);

		String fileName = "批次查询数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

		Map<String, Object> fmap = null;
		for (Map<String,Object> re : exportList) {
			fmap = new HashMap<String, Object>();
			fmap.put("proName", re.get("proName"));
			fmap.put("batch_nub", re.get("batch_nub"));
			fmap.put("nubs", re.get("nubs"));
			fmap.put("botNums", re.get("botNums"));
			fmap.put("scanCompanyName",re.get("scanCompanyName") );
			fmap.put("depotName",re.get("depotName") );
			fmap.put("nodeName",re.get("nodeName") );
			Integer nodeType = (Integer) re.get("nodeType");
			if(nodeType == null){
				fmap.put("toOrFrom","" );
			}else{
				if(nodeType == 1){
					fmap.put("toOrFrom",re.get("to") );
				}else if(nodeType == 2){
					fmap.put("toOrFrom",re.get("from") );
				}else{
					fmap.put("toOrFrom","" );
				}
			}

			fmap.put("scan_time", DateUtils.formatTimeInMillis((Long)re.get("scan_time")));

			list.add(fmap);
		}

		String columnNames[] = {"产品名称", "批次号", "箱数", "瓶数","扫码单位" ,"扫码地点","操作类型","收/发货对象", "操作时间"};//列名
		String keys[] = {"proName", "batch_nub", "nubs","botNums","scanCompanyName","depotName","nodeName","toOrFrom","scan_time"};//map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				bos.flush();
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}

		return null;
	}

	/**
	 * 导航栏点击进入物流查询页
	 * @return
	 */
	@GetMapping("/lgssel")
	public ModelAndView lgsLogistic(){

		Map<String, Object> model = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list",new ArrayList<LgsLogistics>());

		List<String> bottleNoList = new ArrayList<>();
		map.put("bottleNoList",bottleNoList);
		map.put("proName", "");
		map.put("batchNo", "");

		model.put("resultMap", map);
		return new ModelAndView("lgs_logistics").addAllObjects(model);
	}

	/**
	 * 物流查询  点击查询
	 * @param request
	 * @param bottleNo 瓶码
	 * @param boxNo 箱码
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/logistics")
	public ModelAndView logistics(HttpServletRequest request,String bottleNo, String boxNo){

//		if((bottleNo == null || bottleNo.equals(""))&& (boxNo == null || boxNo.equals(""))){
//			throw new BizzException(BizzException.error_code_invalid_params, "请输入箱码或瓶码！");
//		}
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);
		Map<String, Object> map = lgsService.getLogistics(userSession.getCompanyId(),bottleNo, boxNo);

		model.put("resultMap", map);
		model.put("boxNo", boxNo);
		model.put("bottleNo", bottleNo);
		return new ModelAndView("lgs_logistics").addAllObjects(model);
	}

	/**
	 * 获取操作地点
	 * @param request
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getDepotList")
	public HttpResponseBodyWrapper  getDepotList(HttpServletRequest request){

		UserSession userSession = getUserSession(request);
		List<LgsDepot> list = LgsDepotService.getList(userSession.getCompanyId(),1);
		return new HttpResponseBodyWrapper(list);
	}

	/**
	 * 根据箱码获取瓶码
	 */
	@ResponseBody
	@GetMapping("/getBottleByBox")
	public HttpResponseBodyWrapper  getBottleByBox(HttpServletRequest request,String bQrcodeId,Integer companyId){

		List<LgsRelate> list = lgsService.getBottleByBox(bQrcodeId ,companyId);
		return new HttpResponseBodyWrapper(list);
	}

	/**
	 * 根据托盘码获取箱码
	 * @param trayQrcode
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getBoxByTray")
	public HttpResponseBodyWrapper  getBoxByTray(HttpServletRequest request,String trayQrcode){

		UserSession userSession = getUserSession(request);
		List<LgsRelate> list = lgsService.getBoxByTray(trayQrcode ,userSession.getCompanyId());
		return new HttpResponseBodyWrapper(list);
	}

	/**
	 * 关联管理 瓶箱关联
	 * @param cTimeS 操作开始时间
	 * @param cTimeE 操作结束时间
	 * @param depot 操作地点id
	 * @param cAdmin 操作人id
	 * @param page
	 * @return
	 */
	@GetMapping("/relateBox")
	public ModelAndView getList(HttpServletRequest request,String cTimeS, String cTimeE, Integer depot, String cAdmin,Integer page) throws Exception {

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("cTimeS", cTimeS);
		model.put("cTimeE", cTimeE);
		model.put("depot", depot);
		model.put("cAdmin", cAdmin);

		UserSession userSession = getUserSession(request);
		page = (page == null || page < 1) ? 1 : page;
		if(StringUtils.isNotBlank(cTimeS)){
			cTimeS = String.valueOf(DateUtils.stringToLong(cTimeS, "yyyy-MM-dd HH:mm:ss"));
		}
		if(StringUtils.isNotBlank(cTimeE)){
			cTimeE = String.valueOf(DateUtils.stringToLong(cTimeE, "yyyy-MM-dd HH:mm:ss"));
		}
		Pageable<LgsRelate> pagelist = lgsService.getRelateBox(userSession.getCompanyId(),cTimeS, cTimeE,depot,cAdmin,page);

		model.put("pagelist", pagelist);

		return new ModelAndView("lgs_relate_box").addAllObjects(model);
	}

	/**
	 * 关联管理 托盘关联
	 * @param cTimeS 操作开始时间
	 * @param cTimeE 操作结束时间
	 * @param depot 操作地点id
	 * @param cAdmin 操作人id
	 * @param page
	 * @return
	 */
	@GetMapping("/relateTray")
	public ModelAndView getRelateTray(HttpServletRequest request,String cTimeS, String cTimeE, Integer depot, String cAdmin,Integer page) throws Exception {

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("cTimeS", cTimeS);
		model.put("cTimeE", cTimeE);
		model.put("depot", depot);
		model.put("cAdmin", cAdmin);
		UserSession userSession = getUserSession(request);
		page = (page == null || page < 1) ? 1 : page;
		if(StringUtils.isNotBlank(cTimeS)){
			cTimeS = String.valueOf(DateUtils.stringToLong(cTimeS, "yyyy-MM-dd HH:mm:ss"));
		}
		if(StringUtils.isNotBlank(cTimeE)){
			cTimeE = String.valueOf(DateUtils.stringToLong(cTimeE, "yyyy-MM-dd HH:mm:ss"));
		}
		Pageable<LgsRelate> pagelist = lgsService.getRelateTray(userSession.getCompanyId(),cTimeS, cTimeE,depot,cAdmin,page);

		model.put("pagelist", pagelist);
		return new ModelAndView("lgs_relate_tray").addAllObjects(model);
	}

	/**
	 * 数据导出 瓶箱关联
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/relateBoxExport")
	public String relateBoxExport(HttpServletRequest request, HttpServletResponse response ,
								String cTimeS, String cTimeE, Integer depot, String cAdmin) throws Exception {

		if(StringUtils.isNotBlank(cTimeS)){
			cTimeS = String.valueOf(DateUtils.stringToLong(cTimeS, "yyyy-MM-dd HH:mm:ss"));
		}
		if(StringUtils.isNotBlank(cTimeE)){
			cTimeE = String.valueOf(DateUtils.stringToLong(cTimeE, "yyyy-MM-dd HH:mm:ss"));
		}

		UserSession userSession = getUserSession(request);

		List<LgsRelate> exportList = lgsService.relateBoxExport(userSession.getCompanyId(), cTimeS, cTimeE, depot, cAdmin);

		String fileName = "瓶箱关联数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

		Map<String, Object> fmap = null;
		for (LgsRelate re : exportList) {
			fmap = new HashMap<String, Object>();
			Long tid = NumberUtils.toLong(re.getId().toString(), 0L);
			fmap.put("id", tid);
			fmap.put("bQrcodeId", re.getbQrcodeId());
			fmap.put("boxNum", re.getBoxNum());
			fmap.put("depotName", re.getDepotName());
			fmap.put("bingCompanyName", re.getBingCompanyName());
			fmap.put("ts", DateUtils.formatTimeInMillis((Long)re.getTs()));
			fmap.put("cAdmin", re.getcAdmin());

			list.add(fmap);
		}

		String columnNames[] = {"ID", "箱码", "瓶数", "操作地点","所属公司","操作时间" ,"操作人"};//列名
		String keys[] = {"id", "bQrcodeId", "boxNum","depotName","bingCompanyName","ts","cAdmin"};//map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				bos.flush();
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}

		return null;
	}


	/**
	 * 数据导出 托盘关联
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/relateTrayExport")
	public String relateTrayExport(HttpServletRequest request, HttpServletResponse response ,
								  String cTimeS, String cTimeE, Integer depot, String cAdmin) throws Exception {

		if(StringUtils.isNotBlank(cTimeS)){
			cTimeS = String.valueOf(DateUtils.stringToLong(cTimeS, "yyyy-MM-dd HH:mm:ss"));
		}
		if(StringUtils.isNotBlank(cTimeE)){
			cTimeE = String.valueOf(DateUtils.stringToLong(cTimeE, "yyyy-MM-dd HH:mm:ss"));
		}

		UserSession userSession = getUserSession(request);

		List<LgsRelate> exportList = lgsService.relateTrayExport(userSession.getCompanyId(), cTimeS, cTimeE, depot, cAdmin);

		String fileName = "托盘关联数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

		Map<String, Object> fmap = null;
		for (LgsRelate re : exportList) {
			fmap = new HashMap<String, Object>();
			Long tid = NumberUtils.toLong(re.getId().toString(), 0L);
			fmap.put("id", tid);
			fmap.put("trayQrcode", re.getTrayQrcode());
			fmap.put("boxNum", re.getBoxNum());
			fmap.put("depotName", re.getDepotName());
			fmap.put("ts", DateUtils.formatTimeInMillis((Long)re.getTs()));
			fmap.put("cAdmin", re.getcAdmin());

			list.add(fmap);
		}

		String columnNames[] = {"ID", "托盘码", "箱数", "操作地点","操作时间" ,"操作人"};//列名
		String keys[] = {"id", "trayQrcode", "boxNum","depotName","ts","cAdmin"};//map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				bos.flush();
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}

		return null;
	}

	
}
